<template>
	<view class="body">
		<view class="addressAndOtherAndSearch">
			<view class="address">
				<image src="@/static/public/orientation.png" alt="定位" mode="widthFix" @click="controlAddress" />
				<span @click="controlAddress">{{city}}</span>
				<image src="@/static/public/right_arrow.png" alt="右" mode="widthFix" @click="controlAddress" />
			</view>
			<view class="search">
				<image src="@/static/public/search.png" alt="搜索" mode="widthFix" />
			</view>
			<view class="other">
				<image src="@/static/public/add.png" alt="加号" mode="widthFix" />
			</view>
		</view>
		<view class="search">
			<image src="@/static/public/search.png" alt="搜索" mode="widthFix" />
			<view></view>
			请输入内容
		</view>
		<view class="carousel-map">
			<u-swiper :list="carouselList" indicator indicatorMode="line" circular height="100%"></u-swiper>
		</view>
		<view class="feature">
			<view>
				<view @click="publish()">
					<view>
						<view><b>发布需求</b></view>
						<view>点击快速发布任务</view>
					</view>
				</view>
				<view>
					<view>
						<view><b>线上任务</b></view>
					</view>
					<view>
						<view><b>线下任务</b></view>
					</view>
				</view>
			</view>
			<view>
				<view>
					<view>
						<image src="@/static/home/online2.png" alt="线上2" mode="widthFix" />
					</view>
					<view>线上任务</view>
				</view>
				<view>
					<view>
						<image src="@/static/home/offline2.png" alt="线下2" mode="widthFix" />
					</view>
					<view>线下任务</view>
				</view>
				<view @click="gotoIdle">
					<view>
						<image src="@/static/home/inidle.png" alt="闲置" mode="widthFix" />
					</view>
					<view>闲置物品</view>
				</view>
				<view>
					<view>
						<image src="@/static/home/invest.png" alt="投资" mode="widthFix" />
					</view>
					<view>投资融资</view>
				</view>
			</view>
		</view>
		<view class="navigation" ref="navigation" :style="navigationStyle">
			<scroll-view scroll-x="true">
				<view :style="{ color: page.sortId === 0 ? '#000' : '#888A94' }" @click="toggleSort({id:0})">全部
				</view>
				<view v-for="(item,index) in parentSortList"
					:style="{ color: item.id === page.sortId ? '#000' : '#888A94' }" @click="toggleSort(item)">
					{{item.name}}
				</view>
			</scroll-view>

			<view>
				<image src="@/static/public/female.png" alt="菜单" mode="widthFix" />
			</view>
		</view>

		<view class="quest">
			<view v-for="(item,index) in questList" :key="index" @click="details(item)">
				<view>
					<view>
						<image :src="item.initiator.avatar" alt="头像" mode="aspectFill" />
					</view>
					<view><b>￥{{item.price}}</b></view>
					<view>
						<span>{{calculationTime(item.cutoffTime)}}</span>
					</view>
				</view>
				<view>
					<view>{{item.title}}</view>
				</view>
				<view>{{ formatDate(item.createTime) }}</view>
				<view>
					<view>
						<span v-if="item.address.coordinate == null">
							线上需求
						</span>
						<span v-else>
							<image src="@/static/public/orientation.png" alt="定位" mode="heightFix" />
							{{ getMapDistance(item.address.coordinate)}}km
							<span style="display: inline-block;width: 2vw;"></span>
							{{item.address.name}}
						</span>

					</view>
					<view>{{item.initiator.name}}</view>
				</view>
			</view>
		</view>
		<view class="loading">
			<u-loading-icon v-if="this.questList.length < this.page.total"></u-loading-icon>
			<u-loadmore loadmoreText="没有更多了" dashed line v-else />
		</view>
		<u-back-top :scroll-top="scrollTop" top="600" icon="../../static/home/top.png"
			:iconStyle="{width: '16vw',height:'16vw'}" :customStyle="{backgroundColor: 'rgba(0,0,0,0)'}"></u-back-top>
		<image @click="gotoMyorder" class="questList" src="@/static/home/quest_list.png" mode="widthFix">
	</view>
</template>

<script>
	import {
		rear
	} from '@/config/api.js';
	export default {
		data() {
			return {
				isSticky: false, //导航栏是否吸顶
				threshold: 0, //导航栏高度
				parentSortList: [], //任务列表
				page: {
					sortId: 0, //分类id
					current: 0, //第几页
					pageSize: 5, //每页条数
					total: 0 //总条数
				},
				questList: [],
				scrollTop: 0,
				carouselList: [],
				pos: {
					latitude: 0,
					longitude: 0,
				},
				city: "",
				user: {},
				total: 0
			}
		},
		onPullDownRefresh() {
			uni.removeStorageSync('homeRefresh');
			uni.pageScrollTo({
				scrollTop: 0
			});
			this.page = {
				sortId: 0,
				current: 0,
				pageSize: 5,
				total: 0
			}
			uni.stopPullDownRefresh();
			uni.request({
				url: rear + "/quest/getQuestTotal", // API 地址
				method: 'GET', // 请求方法
				data: {
					sortId: this.page.sortId
				},
				success: (res) => {
					this.page.total = res.data.data
				}
			});
			this.questList = [];
			this.getQuestByHomeList();
		},
		onShow() {
			this.user = uni.getStorageSync('user')
			if (this.user != null && this.user != '') {
				this.city = (this.user.city.name != null && this.user.city.name != '' ?
					this.user.city.name : "请选择")
			} else {
				this.city = "请登录"
			}

			if (uni.getStorageSync('homeRefresh')) {
				uni.removeStorageSync('homeRefresh');
				uni.pageScrollTo({
					scrollTop: 0
				});
				this.page = {
					sortId: 0,
					current: 0,
					pageSize: 5,
					total: 0
				}
				uni.request({
					url: rear + "/quest/getQuestTotal", // API 地址
					method: 'GET', // 请求方法
					data: {
						sortId: this.page.sortId
					},
					success: (res) => {
						this.page.total = res.data.data
					}
				});
				this.questList = [];
				this.getQuestByHomeList();
			}


		},
		onLoad() {
			//获取当前位置
			const promise = new Promise((resolve, reject) => {
				uni.getLocation({
					type: 'gcj02',
					success: res => {
						this.pos = res;
						resolve();
					}
				});
			});
			promise.then(() => {
				uni.request({
					url: rear + "/quest/getQuestTotal", // API 地址
					method: 'GET', // 请求方法
					data: {
						sortId: this.page.sortId
					},
					success: (res) => {
						this.page.total = res.data.data
					}
				});
				//获取标签列表
				this.getAllParentSort();
				//获取需求列表
				this.getQuestByHomeList();

				//获取轮播图
				uni.request({
					url: rear + "/carousel/getCarouselList", // API 地址
					method: 'GET', // 请求方法
					success: (res) => {
						for (let i = 0; i < res.data.data.length; i++) {
							this.carouselList.push(res.data.data[i].url)
						}
					}
				});
			});
		},
		methods: {
			controlAddress() {
				if (this.city == "请登录") {
					uni.showToast({
						title: '请登录',
						icon: 'none',
						duration: 2000,
					});
					uni.navigateTo({
						url: '/pages/mine/login'
					});
				} else {


					uni.navigateTo({
						url: '/pages/address/index'
					})
				}
			},
			details(item) {
				if (uni.getStorageSync('user').id == null || uni.getStorageSync('user').id == "") {
					uni.showToast({
						title: '请登录',
						icon: 'none',
						duration: 2000,
					});
					uni.navigateTo({
						url: '/pages/mine/login'
					});
				} else {
					uni.setStorageSync('questId', item.id);
					uni.navigateTo({
						url: '/pages/home/details',
					});
				}


			},
			gotoMyorder() {
				uni.navigateTo({
					url: '/pages/myorder/myorder',
				});
			},
			gotoIdle() {
				uni.navigateTo({
					url: '/pages/idle/index',
				});
			},
			//进行经纬度转换为距离的计算
			Rad(d) {
				return d * Math.PI / 180.0; //经纬度转换成三角函数中度分表形式。
			},
			/*
			 计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
			 默认单位km
			*/
			getMapDistance(coordinate) {
				let lat1 = +this.pos.latitude;
				let lat2 = parseFloat(coordinate.split(",")[1]);
				let lon1 = +this.pos.longitude;
				let lon2 = parseFloat(coordinate.split(",")[0]);
				let R = 6378137;
				let radLat1 = lat1 * Math.PI / 180.0;
				let radLat2 = lat2 * Math.PI / 180.0;
				let radLon1 = lon1 * Math.PI / 180.0;
				let radLon2 = lon2 * Math.PI / 180.0;
				// 计算两点间的弧度差
				let a = radLat1 - radLat2;
				let b = radLon1 - radLon2;
				// Haversine 公式
				let s = 2 * R * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
					Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
				return (s / 1000).toFixed(1); // 返回距离，单位为千米
			},

			publish() {
				if (uni.getStorageSync('user').id == null || uni.getStorageSync('user').id == "") {
					uni.showToast({
						title: '请登录',
						icon: 'none',
						duration: 2000,
					});
					uni.navigateTo({
						url: '/pages/mine/login'
					});
				} else {
					if (this.user.standing != null) {
						uni.navigateTo({
							url: '/pages/home/publish'
						});
					}else{
						uni.showToast({
							title: '请先完成实名认证',
							icon: 'none',
							duration: 2000,
						});
						uni.navigateTo({
							url: '/pages/standing/index'
						});
					}
				}
			},
			toggleSort(item) {
				this.page = {
					sortId: item.id,
					current: 0,
					pageSize: 5,
				}
				uni.request({
					url: rear + "/quest/getQuestTotal", // API 地址
					method: 'GET', // 请求方法
					data: {
						sortId: this.page.sortId
					},
					success: (res) => {
						if (res.data.data == null) {
							res.data.data = 0
						}
						this.page.total = res.data.data
						this.questList = []
						this.getQuestByHomeList()
					}
				});
			},
			getAllParentSort() {
				uni.request({
					url: rear + "/sort/getAllParentSort", // API 地址
					method: 'GET', // 请求方法
					success: (res) => {
						this.parentSortList = res.data.data;
					}
				});
			},
			getQuestByHomeList() {
				uni.request({
					url: rear + "/quest/getQuestByHomeList", // API 地址
					method: 'GET', // 请求方法
					data: this.page,
					success: (res) => {
						// 所有请求完成后，将数据推送到 questList
						this.questList.push(...res.data.data);
					}
				});
			},

			calculationTime(time) {
				let currentTime = new Date(time).getTime() - new Date().getTime(); //当前时间
				let totalSeconds = Math.floor(currentTime / 1000);
				let days = Math.floor(totalSeconds / (3600 * 24));
				let hours = Math.floor((totalSeconds % (3600 * 24)) / 3600);
				let minutes = Math.floor((totalSeconds % 3600) / 60);
				let text = "";
				if (days != 0) {
					text = days + "天"
				}
				if (hours != 0) {
					text += hours + "小时"
				} else if (text != "") {
					text += "0小时"
				}
				if (minutes != 0) {
					text += minutes + "分钟";
				}
				return text + "后截止"
			},
			formatDate(isoString) {
				const date = new Date(isoString);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			loading() {
				if (this.questList.length < this.page.total) {
					this.page.current += 1
					this.getQuestByHomeList()
				}
			}
		},

		computed: {
			// 计算导航栏的动态样式
			navigationStyle() {
				if (this.isSticky) {
					return {
						paddingTop: '10vw',
						paddingLeft: '5vw',
						paddingRight: '5vw',
						margin: '4vw 0 0 0',
						borderBottom: 'rgba(0, 0, 0, 0.2) 1px solid'
					};
				} else {
					return {
						padding: '0 1vw 0 1vw'
					};
				}
			}
		},

		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
			// 判断是否达到吸顶的临界高度
			this.isSticky = this.scrollTop >= this.threshold - 30;
		},
		onReady() {
			const query = uni.createSelectorQuery().in(this);
			query.select('.navigation').boundingClientRect((data) => {
				if (data && data.top !== undefined) {
					this.threshold = data.top;
				}
			}).exec();
		},
		// 监听页面滚动到底部的事件
		onReachBottom() {
			this.loading(); // 当页面滚动到底部时，加载更多数据
		}
	}
</script>

<style lang="scss">
	.body {

		background-image: url("@/static/public/background.png");
		background-size: 100%;
		background-repeat: no-repeat;

		padding: 4vw 0;

		>* {
			margin: 4vw 4vw 0 4vw;
		}

		.addressAndOtherAndSearch {
			display: flex;
			flex-wrap: wrap;
			height: 10vw;
			line-height: 10vw;

			.address {
				width: 73%;
				font-size: 4vw;

				image:nth-of-type(1) {
					width: 2.5vw;
					vertical-align: -0.1em;
					margin-right: 0.5vw;
				}

				image:nth-of-type(2) {
					width: 1.5vw;
					margin-left: 0.5vw;
				}
			}

			.search {
				width: 18%;
				text-align: right;

				image {
					width: 6vw;
					vertical-align: -2vw;
				}
			}

			.other {
				width: 9%;
				text-align: right;

				image {
					width: 6vw;
					vertical-align: -2vw;
				}
			}
		}

		>.search {
			margin-top: 1vw;
			background-color: #FFFFFF;
			height: 10vw;
			box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
			border-radius: 2vw;
			padding: 2.5vw;
			box-sizing: border-box;
			font-size: 4vw;
			color: #AAAAAA;
			display: flex;
			flex-wrap: wrap;

			view {
				width: 1vw;
			}

			image {
				width: 5vw;
			}
		}

		.carousel-map {
			height: 41vw;
			background-color: red;
			background-size: 100% 100%;
			border-radius: 10vw;
		}

		.feature {
			background-color: #FFFFF;
			box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
			border-radius: 3vw;
			padding: 3vw 0;
			box-sizing: border-box;

			>view:nth-of-type(1) {
				height: 40vw;
				display: flex;
				flex-wrap: wrap;

				>view {
					height: 100%;
				}

				>view:nth-of-type(1) {
					width: 56%;
					background-image: url(@/static/home/publish.png);
					background-size: 100% 100%;
					position: relative;

					>view {
						width: 100%;
						position: absolute;
						bottom: 6vw;
						text-align: center;
						color: #FFFFFF;

						>view:nth-of-type(1) {
							font-size: 6vw;
						}

						>view:nth-of-type(2) {
							font-size: 3vw;
						}
					}
				}

				>view:nth-of-type(2) {
					width: 44%;

					>view {
						background-size: 100% 100%;
						height: 50%;
						position: relative;
						text-align: center;
						color: #FFFFFF;

						view {
							width: 100%;
							position: absolute;
							bottom: 4vw;
							text-align: center;
						}
					}

					>view:nth-of-type(1) {
						background-image: url(@/static/home/online.png);
					}

					>view:nth-of-type(2) {
						background-image: url(@/static/home/offline.png);
					}
				}
			}

			>view:nth-of-type(2) {
				display: flex;
				flex-wrap: wrap;
				text-align: center;

				>view {
					width: 25%;
					font-size: 3.5vw;

					image {
						width: 8vw;
					}
				}
			}
		}


		.navigation {
			position: sticky;
			top: 0;
			z-index: 99;
			box-sizing: border-box;
			background-color: #FFFFFF;
			display: flex;
			flex-wrap: wrap;

			>* {
				height: 10vw;
				line-height: 10vw;
			}

			>scroll-view {
				width: 93%;
				color: #888A94;
				white-space: nowrap;

				view {
					display: inline-block;
					padding: 0 1vw;
				}
			}

			>view {
				text-align: right;
				width: 7%;

				image {
					width: 4vw;
					vertical-align: -0.5vw;
				}
			}
		}

		.quest {
			>view {
				background-color: #FFFFF;
				box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
				border-radius: 3vw;
				margin-bottom: 3vw;
				padding: 3vw;

				>view:nth-of-type(1) {
					display: flex;
					flex-wrap: wrap;
					padding-bottom: 1vw;
					line-height: 6.5vw;

					>view:nth-of-type(1) {
						width: 10%;

						image {
							width: 6.5vw;
							height: 6.5vw;
							border-radius: 3.25vw;
						}
					}

					>view:nth-of-type(2) {
						width: 45%;
						color: #FF0000;
						font-size: 5vw;
					}

					>view:nth-of-type(3) {
						width: 45%;
						text-align: right;

						span {
							display: inline-block;
							padding: 0 1.5vw;
							background-color: #FFEFEF;
							border-radius: 3.25vw;
							height: 6.5vw;
							text-align: center;
							color: #FE5C0B;
							font-size: 3vw;
						}
					}
				}

				>view:nth-of-type(3) {
					margin-top: 1vw;
					color: #AAAAAA;
					font-size: 3vw;
				}

				>view:nth-of-type(4) {
					height: 5vw;
					line-height: 5vw;
					padding-top: 1vw;
					display: flex;
					flex-wrap: wrap;
					color: #AAAAAA;

					>view:nth-of-type(1) {
						width: 60%;
						font-size: 3vw;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;

						image {
							height: 3vw;
							vertical-align: -0.3vw;
						}
					}

					>view:nth-of-type(2) {
						width: 40%;
						text-align: right;
						font-size: 3vw;
					}
				}
			}

		}

		.loading {
			text-align: center;

			image {
				width: 10vw;
			}
		}

		.questList {
			width: 16vw;
			position: fixed;
			bottom: 10vw;
			right: 3.1vw;
		}
	}
</style>